package cn.bytecollege.util;

import lombok.extern.log4j.Log4j2;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

//文件上传
@Log4j2
public class FileUpLoad {
    public static String fileUpLoad(String path,MultipartFile file) {
        String originalFilename = UUID.randomUUID()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String separator = File.separator;
        try {
            String absPath = ResourceUtils.getURL("classpath:").getPath();
            int index = absPath.lastIndexOf("/target");
            String substring = absPath.substring(0, index);
            //要保存的地址
            String localPath = substring + path;

            //文件保存磁盘
            File saveFile = new File(localPath,originalFilename);
            file.transferTo(saveFile);
            return path.substring(path.lastIndexOf("/images")) +"/"+ originalFilename;
        } catch (FileNotFoundException e) {
            return "上传失败";
        } catch (IOException e) {
            return "上传失败";
        }
    }
}
